package com.samon.netty.echo;
/*
               _.---..._
           ./^         ^-._
         ./^C===.         ^\.   /\
        .|'     \\        _ ^|.^.|
   ___.--'_     ( )  .      ./ /||
  /.---^T\      ,     |     / /|||
 C'   ._`|  ._ /  __,-/    / /-,||
      \ \/    ;  /O  / _    |) )|,
       i \./^O\./_,-^/^    ,;-^,'
        \ |`--/ ..-^^      |_-^
         `|  \^-           /|:
          i.  .--         / '|.
           i   =='       /'  |\._
         _./`._        //    |.  ^-ooo.._
  _.oo../'  |  ^-.__./X/   . `|    | d
				 比克叔叔保佑
				 代码无BUG!
 */

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;

/**
 * @author Mr.Wu on 2018/9/14
 */
public class EchoClient {
	
	private final String host;
	private final int port;

	public EchoClient(String host, int port) {
		this.host = host;
		this.port = port;
	}

	public void start() throws InterruptedException {
		
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			// 创建 Bootstrap
			Bootstrap b = new Bootstrap();
			// 指定 EventLoopGroup 以处理客户端事件; 需要适用于NIO的实现
			b.group(group)
			 // 适用于NIO传输的 Channel 类型
			 .channel(NioSocketChannel.class)
			 // 设置服务器的 InetSocketAddress
			 .remoteAddress(new InetSocketAddress(host, port))
			 // 在创建 Channel 时, 向 ChannelPipeline 中添加一个 EchoClientHandler(自己实现) 实例
			 .handler(new ChannelInitializer<SocketChannel>() {
				
				 @Override protected void initChannel(SocketChannel socketChannel) {
					 socketChannel.pipeline().addLast(new EchoClientHandler());
				 }
			 });
			// 连接到远程节点, 阻塞等待直到连接完成阻塞
			ChannelFuture f = b.connect().sync();
			// 阻塞, 直到 Channel 关闭
			f.channel().closeFuture().sync();
		} finally {
			// 关闭线程池并且释放所有的资源
			group.shutdownGracefully().sync();
		}
	}

	public static void main(String[] args) throws InterruptedException {
		String host = "192.168.10.143";
		int port = 8888;
		new EchoClient(host, port).start();
	}
	
}
